package com.zrrd.yunchmall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.yunchmall.user.entity.Menu;
import com.zrrd.yunchmall.user.entity.Resource;
import com.zrrd.yunchmall.user.mapper.MenuMapper;
import com.zrrd.yunchmall.user.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 后台菜单表 服务实现类
 * </p>
 *
 * @author YeKong
 * @since 2024-01-15
 */
@Service
@Primary
@SuppressWarnings("all")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询菜单树
     * @return
     */
    @Override
    public List<Menu> getTreeList() {
        //命中redis缓存,(redis数据库中已经存在了MenuTree，直接取出并返回)
        if(redisTemplate.hasKey("MenuTree")) {
            return redisTemplate.opsForList().range("MenuTree", 0, -1);
        }
        //查询一级菜单
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select("id", "parent_id", "title", "level", "sort", "name", "icon", "hidden");
        queryWrapper.eq("parent_id", 0);
        queryWrapper.or();
        queryWrapper.eq("level", 0);
        List<Menu> l1MenuList = super.list(queryWrapper);
        //对一级菜单进行循环遍历，查到每个一级菜单的二级菜单列表
        l1MenuList.forEach(menu -> {
            //清除之前的查询条件
            queryWrapper.clear();
            queryWrapper.select("id", "parent_id", "title", "level", "sort", "name", "icon", "hidden");
            queryWrapper.eq("parent_id", menu.getId());
            menu.setChildren(super.list(queryWrapper));
        });
        //如果缓存中不存在这个MenuTree，那就在查询到之后缓存到Redis数据库中
        redisTemplate.opsForList().rightPushAll("MenuTree", l1MenuList);
        //设置这个缓存的有效期为5分钟（根据经验设置缓存时间）
        redisTemplate.expire("MenuTree", 5, TimeUnit.MINUTES);
        return l1MenuList;
    }


    @Override
    public List<Menu> getmenulist(long id) {
        return menuMapper.selectMenusByid(id);
    }
}
